#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/eventfd.h>

int main() {
    // 创建有名事件
    int fd = eventfd(0, EFD_SEMAPHORE | EFD_CLOEXEC);
    if (fd < 0) {
        fprintf(stderr, "Failed to create eventfd.\n");
        return -1;
    }

    // 创建子进程
    pid_t pid = fork();
    if (pid < 0) {
        fprintf(stderr, "Failed to create child process.\n");
        return -1;
    } else if (pid == 0) {
        // 子进程发送事件信号
        sleep(1);
        uint64_t value = 1;
        if (write(fd, &value, sizeof(value)) < 0) {
            fprintf(stderr, "Failed to write eventfd.\n");
            return -1;
        }
        exit(0);
    } else {
        // 父进程等待事件信号并处理
        uint64_t value;
        if (read(fd, &value, sizeof(value)) < 0) {
            fprintf(stderr, "Failed to read eventfd.\n");
            return -1;
        }
        printf("Parent process: received eventfd signal, value = %llu\n", (unsigned long long)value + 1);
        // TODO: 处理事件信号
    }

    return 0;
}
